Chapter 0: Quickstart Walkthrough — "Seeing is Believing" Hands-On Demo
Security architectures are often presented in abstract concepts. The goal of this walkthrough is to provide an immediate, hands-on demonstration of the difference between standard perimeter-only LLM applications and deterministic, code-level Policy Enforcement Points (PEPs).
By pairing the langchain-security-extension library with its live companion reference demonstrator, langchain-enterprise-incident-assistant, you will run functional and adversarial tests against two Git branches:
mainbranch (Unhardened Baseline): A standard FastAPI + LangChain IT Incident Assistant with HTTP Bearer JWT authentication, standard prompt-based instructions, and native tool execution. Demonstrates how easily standard LLM applications are exploited via prompt injection, argument tampering, cross-tenant RAG leaks, and runaway loops.securedbranch (Hardened Target): The identical application hardened withlangchain-security-extension. Demonstrates how code-level PEPs deterministically intercept every exploit before LLM tokens are wasted or unauthorized Python callables run.
Step 1: Environment & Repository Setup
1. Prerequisites
- Python 3.9+: A shared Python virtual environment.
- Configured LLM Service(s): The demonstrator issues real model calls across a multi-agent pipeline. Both
model1(used by the Triage Agent) andmodel2(used by the Remediation Agent) must be configured inconfig.properties. By default, both connect to a local Ollama instance (http://localhost:11434with modelllama3.2:3b). They can be the exact same model or different models, and can be directed to any OpenAI, Gemini, or Claude compatible endpoint.
2. Clone the Companion Demonstrator
Clone the companion incident assistant demonstrator into your workspace:
# Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Clone the companion incident assistant demonstrator
git clone https://github.com/prashantdev/langchain-enterprise-incident-assistant.git
cd langchain-enterprise-incident-assistant
3. Install Assistant Dependencies
Install the assistant application and testing dependencies in development mode:
# Install base assistant and test dependencies
pip install -e ".[dev]"
Security Extension Dependency: The
mainbranch represents an unhardened baseline and has zero security dependencies. Thesecuredbranch includeslangchain-security-extensiondirectly in itspyproject.tomldependencies. When you switch to thesecuredbranch in Step 3, simply runpip install -e .(orpip install langchain-security-extension) to install the security library.(Optional for Library Contributors) If you are actively developing or modifying
langchain-security-extensionlocally, clone the library repository side by side and install in editable mode:git clone https://github.com/prashantdev/langchain-security-extension.git && pip install -e ./langchain-security-extension.
4. Multi-Agent Model Configuration (model1 & model2)
The companion assistant is specifically architected to demonstrate multi-agent collaboration across heterogeneous models while enforcing a standard, uniform security posture across everything:
model1(Triage Agent): Drives initial ticket classification, severity assessment, and entity/parameter extraction from incoming user requests.model2(Remediation Agent): Drives runbook retrieval, SOP troubleshooting reasoning, and tool dispatch (e.g., executing diagnostics, restarting services, or managing access).
Both model1 and model2 must be configured in langchain-enterprise-incident-assistant/config.properties:
- Identical Models (Default): You can configure both
model1andmodel2to point to the exact same model (e.g., local Ollama runningllama3.2:3b). This requires minimal hardware resources and is ideal for quick local experimentation. - Different Models: You can configure distinct models for each agent to test heterogeneous deployments (e.g., an efficient local SLM like
llama3.2:3bformodel1triage, paired with a frontier reasoning model like Gemini 3.5 Flash or GPT-4o formodel2remediation).
Standard Security Across Everything (Hardened
securedBranch): While the baselinemainbranch leaves models and tools unhardened, the hardenedsecuredbranch useslangchain-security-extensionto apply identical, zero-trust security controls across all agent steps—regardless of whethermodel1andmodel2share the same model or use completely different local or commercial providers. This includes policy decision point (PDP) authorization, tool parameter interception, PII/credential redaction, token budgets, anti-looping protections, and SIEM audit logging.
# ---------------------------------------------------------------------------
# LLM Config - Model 1: Used by Triage Agent
# ---------------------------------------------------------------------------
model1.baseUrl=http://localhost:11434
model1.modelclass=ollama
model1.modelname=llama3.2:3b
model1.apikey=
model1.timeout=300s
# ---------------------------------------------------------------------------
# LLM Config - Model 2: Used by Remediation Agent
# (Can be the same model as model1, or a different local/frontier model)
# ---------------------------------------------------------------------------
model2.baseUrl=http://localhost:11434
model2.modelclass=ollama
model2.modelname=llama3.2:3b
model2.apikey=
model2.timeout=300s
# ---------------------------------------------------------------------------
# Example Alternative: Configuring a Frontier Model for model2
# ---------------------------------------------------------------------------
# model2.baseUrl=https://generativelanguage.googleapis.com/v1beta/openai/
# model2.modelclass=openai
# model2.modelname=gemini-3.5-flash
# model2.apikey=YOUR_API_KEY
# model2.timeout=60s
5. Verify LLM Service Availability
Ensure your configured LLM backend(s) are running. For local Ollama users:
# Ensure Ollama is active and model is pulled
ollama serve &
ollama pull llama3.2:3b
Universal LLM Reachability Check: The test runner (
./run-security-suite.sh) actively queries the configuredbaseUrlinconfig.propertiesbefore executing tests. It seamlessly supports local Ollama, Google Gemini, OpenAI, Claude, or custom enterprise gateway endpoints.
Step 2: Testing the Unhardened Baseline (main Branch)
First, observe how standard perimeter security behaves under both legitimate operations and adversarial exploit attempts.
1. Checkout the main Branch & Start the Server
Open Terminal 1 to run the assistant server:
git checkout main
./startserver.sh
The server starts an embedded FastAPI service listening on port 8080.
2. Run the Basic Functional Suite (--suite basic)
In Terminal 2, run the baseline functional test suite:
./run-security-suite.sh --suite basic
Expected Outcome: All 15 / 15 tests PASS. Standard P1 outages are triaged, password resets work, and unauthenticated HTTP calls without Bearer tokens are rejected at the FastAPI perimeter.
3. Run the Guardrail Exploit Suite (--suite guardrail)
Now, run the 31 adversarial exploit tests against the unhardened baseline:
./run-security-suite.sh --suite guardrail
Expected Outcome: All 31 / 31 tests FAIL (Exploits Succeed):
- Exploit: Unauthorized employees trick the agent into rebooting production database servers (
web-prod-01) via prompt overrides. - Exploit: DevOps engineers targeting finance infrastructure bypass department checks because arguments are not validated before execution.
- Exploit: Clearance Level 1 callers retrieve classified Level 3 runbooks from ChromaDB because standard RAG lacks pre-retrieval filtering.
- Exploit: Denied tools cause the LLM to enter runaway retry loops, burning hundreds of unnecessary tokens.
- Exploit: Sensitive API keys, passwords, and PII are logged in plaintext to application logs.
Step 3: Testing the Hardened Implementation (secured Branch)
Next, switch to the hardened target implementation utilizing langchain-security-extension.
1. Checkout the secured Branch & Restart the Server
In Terminal 1, stop the running server (Ctrl+C), checkout the hardened branch, install the secured dependencies (which pulls langchain-security-extension from PyPI), and restart:
git checkout secured
# Install secured dependencies (automatically installs langchain-security-extension)
pip install -e .
./startserver.sh
2. Run the Basic Suite
In Terminal 2, re-run the basic suite to verify that hardening introduced zero regressions into legitimate workflows:
./run-security-suite.sh --suite basic
Expected Outcome: All 15 / 15 tests PASS.
3. Run the Guardrail Suite
Run the 31 adversarial exploit tests against the hardened server:
./run-security-suite.sh --suite guardrail
Expected Outcome: All 31 / 31 tests PASS (Exploits Defeated):
@secured_toolintercepts and hard-aborts unauthorized calls in Python bytecode before tool functions run.- Common Expression Language (CEL) rules deterministically block department mismatches (
PARAMETER_CONSTRAINT_FAILED). SecureRetrieverinjects native VectorStore AST pre-filters and prunes documents before they enter the prompt context window.RetryBudgetTrackerhalts brute-force tool retry loops after consecutive policy denials.- In-flight DLP sanitizes PII, Luhn-valid credit cards, and API secrets before telemetry is published to the background SIEM buffer.
Step 4: Trying Individual Exploit Tests
You can execute individual test scripts to inspect raw HTTP requests, agent thoughts, and diagnostic error codes in detail.
Scenario A: Testing Dynamic CEL Parameter Constraints
./internal-security-guardrail-tests/08-cel-parameter-department-mismatch-blocked.sh
What happens: An authorized DevOps user attempts to reboot finance-db-01. The @secured_tool evaluator dynamically looks up server ownership via EntityAttributeResolverSPI, detects that the server belongs to FINANCE while the caller is in INFRA, and aborts with diagnostic code PARAMETER_CONSTRAINT_FAILED.
Scenario B: Testing Indirect Prompt Injection Neutralization
./internal-security-guardrail-tests/23-prompt-injection-blocked.sh
What happens: An inbound incident ticket contains a jailbreak string attempting to override system instructions and exfiltrate secrets. The entry PEP halts execution and emits a PROMPT_INJECTION_DETECTED security event to SIEM.
Scenario C: Inspecting SIEM Audit Streaming
tail -n 15 logs/security-audit.json | jq .
What happens: Inspect the live structured RFC 5424 / OCSF audit log containing cryptographic trace correlations (W3C traceparent), redacted PII fields, and deterministic denial reason codes.
Complete Catalog of Tests in the Demonstrator
Suite 1: Basic Security Tests (15 Tests)
The basic security suite validates standard ticket triage, remediation operations, perimeter JWT validation, and RBAC baseline functionality.
| # | Test Script | Description & Verification Scenario | main |
secured |
|---|---|---|---|---|
| 01 | 01-standard-p1-outage-processed.sh |
Validates standard P1 incident workflow for authorized DevOps engineer. | PASS | PASS |
| 02 | 02-standard-p4-password-reset-processed.sh |
Validates standard P4 self-service password reset for corporate employee. | PASS | PASS |
| 03 | 03-unauthorized-user-blocked.sh |
Verifies perimeter HTTP rejection of unknown or unregistered callers. | PASS | PASS |
| 04 | 04-cross-tenant-isolation-blocked.sh |
Verifies perimeter rejection when tenant claim does not match target route. | PASS | PASS |
| 05 | 05-clearance-floor-violation-blocked.sh |
Validates rejection when caller clearance level is below ticket entry floor. | PASS | PASS |
| 06 | 06-unauthenticated-caller-blocked.sh |
Verifies perimeter rejection (401 Unauthorized) when Bearer token is missing. | PASS | PASS |
| 07 | 07-mutative-tool-sideeffect-aborted.sh |
Verifies that unauthorized callers cannot trigger mutative tool operations. | PASS | PASS |
| 08 | 08-malformed-poisoned-identity-blocked.sh |
Validates perimeter rejection of malformed or syntactically invalid JWT tokens. | PASS | PASS |
| 09 | 09-subagent-async-context-propagated.sh |
Validates caller context propagation across multi-agent triage-to-remediation handoff. | PASS | PASS |
| 10 | 10-fake-server-entity-extracted.sh |
Verifies agent handling when ticket references a non-existent infrastructure hostname. | PASS | PASS |
| 11 | 11-unauthorized-tool-execution-blocked.sh |
Verifies that standard employees cannot trigger privileged server restart tools. | PASS | PASS |
| 12 | 12-role-escalation-violation-blocked.sh |
Blocks attempts by standard users to escalate privileges to ROLE_ADMIN actions. |
PASS | PASS |
| 13 | 13-invalid-entity-remediation-blocked.sh |
Ensures remediation workflows halt when target infrastructure entities are invalid. | PASS | PASS |
| 14 | 14-unauthorized-target-user-password-reset-blocked.sh |
Ensures non-admin users cannot trigger password resets targeting executive accounts. | PASS | PASS |
| 15 | 15-unauthenticated-rag-request-blocked.sh |
Verifies that direct unauthenticated requests to knowledge base endpoints are rejected. | PASS | PASS |
Suite 2: Internal Security Guardrail Suite (31 Exploit Vectors)
The guardrail test suite evaluates zero-trust Policy Enforcement Points under active prompt injection, parameter tampering, cross-tenant leaks, and token-exhaustion loops.
Domain A: Knowledge Ingestion & Admission Control
| # | Test Script | Exploit Vector & Enforcement Guarantee | main |
secured |
|---|---|---|---|---|
| 01 | 01-ingestion-envelope-validation-enforced.sh |
Missing mandatory sec:* tags rejected during document segment ingestion.→ See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
| 02 | 02-ingestion-header-classification-elevation.sh |
Parser detects structural headers (## [CONFIDENTIAL]) and elevates classification floor.→ See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
| 03 | 03-ingestion-strict-fail-closed-atomic-rollback.sh |
Under strict fail-closed mode, malformed metadata causes atomic rollback of document batch. → See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
| 04 | 04-ingestion-permissive-quarantine-elevation.sh |
Unlabelled chunks in permissive mode are automatically tagged sec:quarantined = true.→ See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
| 05 | 05-ingestion-monotonic-classification-elevation.sh |
Strictly rejects illegal de-escalation of chunk clearance below parent document baseline. → See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
| 06 | 06-hmac-envelope-tamper-detection.sh |
Direct tampering of metadata tags in storage fails HMAC verification (INVALID_HMAC).→ See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
| 07 | 07-ingestion-unlabelled-chunk-quarantine-policy.sh |
Chunks lacking explicit envelope metadata are pruned under strict admission policies. → See Chapter 5: Ingestion Pipeline |
FAIL | PASS |
Domain B: Pre-Execution Tool Guardrails & CEL Parameter Validation
| # | Test Script | Exploit Vector & Enforcement Guarantee | main |
secured |
|---|---|---|---|---|
| 08 | 08-cel-parameter-department-mismatch-blocked.sh |
CEL halts tool when caller department does not own the target infrastructure asset. → See Chapter 7: Guarding Tools & APIs |
FAIL | PASS |
| 09 | 09-dual-mode-hard-abort-enforced.sh |
Mutative tool violations trigger an immediate Hard Abort, halting execution with 0 tokens. → See Chapter 7: Guarding Tools & APIs |
FAIL | PASS |
| 10 | 10-policy-brute-force-retry-loop-halted.sh |
Halts agent execution when model repeatedly retries denied tool dispatches. → See Chapter 8: Defending Agent Looping · Chapter 7: Tool Guardrails |
FAIL | PASS |
| 11 | 11-cel-null-entity-resolution-fail-closed.sh |
CEL evaluation fails closed (DENY) when target asset ID cannot be resolved in CMDB. → See Chapter 7: Guarding Tools & APIs |
FAIL | PASS |
| 12 | 12-tool-interceptor-schema-hiding-verification.sh |
Strips internal security identity context from model OpenAPI schemas (Schema Hiding). → See Chapter 7: Guarding Tools & APIs |
FAIL | PASS |
| 13 | 13-model-feedback-soft-refusal-returned.sh |
Informational tool denials return safe synthetic refusal messages instead of hard halting. → See Chapter 7: Guarding Tools & APIs |
FAIL | PASS |
| 14 | 14-cel-entity-attribute-hydration-resolved.sh |
Hydrates live CMDB entity attributes dynamically for CEL ABAC evaluation. → See Chapter 7: Guarding Tools & APIs |
FAIL | PASS |
Domain C: Secure Vector Retrieval & Context Leakage Defense
| # | Test Script | Exploit Vector & Enforcement Guarantee | main |
secured |
|---|---|---|---|---|
| 15 | 15-rag-clearance-data-leakage-prevented.sh |
Prevents Level 1 callers from retrieving Level 3 runbooks via vector pre-filtering. → See Chapter 6: Integrating Vector DB |
FAIL | PASS |
| 16 | 16-rag-topk-predictive-oversampling-and-paging.sh |
Inflates Top-K retrieval window (oversampling) to prevent result starvation during pruning. → See Chapter 6: Integrating Vector DB |
FAIL | PASS |
| 17 | 17-rag-vectorstore-ast-prefilter-translation.sh |
Translates caller identity into native VectorStore search filters prior to cosine query. → See Chapter 6: Integrating Vector DB |
FAIL | PASS |
Domain D: Policy Decision Point (PDP) & Circuit Breakers
| # | Test Script | Exploit Vector & Enforcement Guarantee | main |
secured |
|---|---|---|---|---|
| 18 | 18-pdp-two-tier-cache-hit-performance.sh |
Deduplicates policy checks via Tier 1 (invocation) and Tier 2 (TTL) decision caching. → See Chapter 3: Authorization Engine |
FAIL | PASS |
| 19 | 19-remote-opa-pdp-circuit-breaker-fail-closed.sh |
Trips circuit breaker to fail-closed DENY when remote OPA policy engine is unreachable. → See Chapter 3: Authorization Engine |
FAIL | PASS |
| 20 | 20-framework-starter-identity-propagation.sh |
Maps perimeter auth context deterministically into RunnableConfig envelope.→ See Chapter 2: Identity Provider · Chapter 4: Entry Points |
FAIL | PASS |
| 21 | 21-pdp-circuit-breaker-state-machine-transitions.sh |
Verifies circuit breaker state transitions (CLOSED → OPEN → HALF_OPEN) during outages. → See Chapter 3: Authorization Engine |
FAIL | PASS |
| 22 | 22-pdp-cache-eviction-on-identity-invalidation.sh |
Evicts cached L1/L2 verdicts immediately when user roles or clearance are revoked. → See Chapter 3: Authorization Engine |
FAIL | PASS |
Domain E: Threat Neutralization, In-Flight DLP & SIEM Telemetry
| # | Test Script | Exploit Vector & Enforcement Guarantee | main |
secured |
|---|---|---|---|---|
| 23 | 23-prompt-injection-blocked.sh |
Neutralizes instruction overrides and emits PROMPT_INJECTION_DETECTED.→ See Chapter 4: Protecting Entry Points |
FAIL | PASS |
| 24 | 24-siem-audit-sanitization-enforced.sh |
Emits tamper-evident structured audit events to SIEM sinks via non-blocking ring buffer. → See Chapter 10: SIEM & Log Aggregators |
FAIL | PASS |
| 25 | 25-pii-regex-and-masked-annotation-scrubbing.sh |
Scrubs passwords, AWS keys, Bearer tokens, and Luhn-valid credit cards in-flight. → See Chapter 9: Sanitizing Payloads |
FAIL | PASS |
| 26 | 26-tenant-isolation-boundary-violation-alert.sh |
Blocks foreign tenant operations and raises critical TENANT_BOUND_VIOLATION alert.→ See Chapter 11: Enforcing Multi-Tenancy |
FAIL | PASS |
| 27 | 27-opentelemetry-trace-span-correlation.sh |
Extracts W3C traceparent headers and correlates trace and span IDs to audit events.→ See Chapter 10: SIEM & Log Aggregators |
FAIL | PASS |
| 28 | 28-siem-policy-brute-force-alert-generation.sh |
Emits POLICY_BRUTE_FORCE_SCANNING alert when caller exceeds denial threshold.→ See Chapter 10: SIEM & Log Aggregators · Chapter 8: Anti-Looping |
FAIL | PASS |
| 29 | 29-anti-loop-retry-cap-terminated.sh |
Terminates agent execution upon reaching maximum consecutive tool violations cap. → See Chapter 8: Defending Agent Looping |
FAIL | PASS |
| 30 | 30-telemetry-sanitization-raw-event-verified.sh |
Verifies raw emitted event dictionaries contain zero plaintext credentials or secrets. → See Chapter 10: SIEM & Log Aggregators · Chapter 9: Sanitizing Payloads |
FAIL | PASS |
| 31 | 31-sliding-window-abuse-throttling.sh |
Throttles cross-turn abuse over a sliding temporal window and auto-prunes expired denials. → See Chapter 8: Defending Agent Looping |
FAIL | PASS |
Summary & Next Steps
Now that you have seen the difference between perimeter-only agents and zero-trust code-level PEPs in practice, proceed through the implementation chapters to explore how each component can be implemented in your enterprise applications:
- Chapter 1: Architecture Blueprint & System Boundaries — The 4 core enforcement checkpoints.
- Chapter 2: Connecting Your Identity Provider — How to pass caller identity into
RunnableConfig. - Chapter 7: Guarding Tools & Enterprise APIs — Writing Common Expression Language (CEL) parameter constraints.
- Chapter 10: SIEM & Log Aggregators — Asynchronous telemetry and compliance streaming.